package com.heyige.facade;

import com.heyige.dto.SystemMonitorDto;
import com.heyige.service.ai.DeepSeekService;
import com.heyige.service.ai.ZhiPuService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.RuntimeMXBean;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class SystemMonitorService {

    private final DeepSeekService deepSeekService;

    private final ZhiPuService zhipuGlmService;

    /**
     * 获取系统状态信息
     *
     * @return 系统状态信息
     */
    public SystemMonitorDto.SystemStatusResponse getSystemStatus() {
        SystemMonitorDto.SystemStatusResponse response = new SystemMonitorDto.SystemStatusResponse();

        // 获取JVM信息
        Runtime runtime = Runtime.getRuntime();
        response.setTotalMemory(runtime.totalMemory());
        response.setFreeMemory(runtime.freeMemory());
        response.setUsedMemory(runtime.totalMemory() - runtime.freeMemory());
        response.setMaxMemory(runtime.maxMemory());

        // 获取系统信息
        OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
        response.setAvailableProcessors(runtime.availableProcessors());
        response.setSystemLoadAverage(osBean.getSystemLoadAverage());

        // 获取运行时间
        RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
        response.setJvmStartTime(LocalDateTime.ofEpochSecond(runtimeBean.getStartTime() / 1000, 0, ZoneOffset.UTC));
        response.setJvmUptime(Duration.ofMillis(runtimeBean.getUptime()));

        // 获取应用信息
        response.setApplicationName("AI Chat System");
        response.setApplicationVersion("1.0.0");
        response.setServerTime(LocalDateTime.now());

        return response;
    }

    /**
     * 获取AI服务连接状态
     *
     * @return AI服务连接状态
     */
    public SystemMonitorDto.AiServiceStatusResponse getAiServiceStatus() {
        SystemMonitorDto.AiServiceStatusResponse response = new SystemMonitorDto.AiServiceStatusResponse();

        // 检查DeepSeek服务状态
        SystemMonitorDto.ServiceStatus deepSeekStatus = new SystemMonitorDto.ServiceStatus();
        deepSeekStatus.setName("DeepSeek");
        deepSeekStatus.setConnected(deepSeekService.isAvailable());
        deepSeekStatus.setLastCheckTime(LocalDateTime.now());
        response.setDeepSeek(deepSeekStatus);

        // 检查智谱GLM服务状态
        SystemMonitorDto.ServiceStatus zhipuStatus = new SystemMonitorDto.ServiceStatus();
        zhipuStatus.setName("Zhipu GLM");
        zhipuStatus.setConnected(zhipuGlmService.isAvailable());
        zhipuStatus.setLastCheckTime(LocalDateTime.now());
        response.setZhipu(zhipuStatus);

        // 计算整体状态
        boolean allConnected = deepSeekStatus.getConnected() && zhipuStatus.getConnected();
        response.setAllConnected(allConnected);
        response.setCheckTime(LocalDateTime.now());

        return response;
    }

    /**
     * 获取系统统计信息
     *
     * @return 系统统计信息
     */
    public SystemMonitorDto.SystemStatisticsResponse getSystemStatistics() {
        SystemMonitorDto.SystemStatisticsResponse response = new SystemMonitorDto.SystemStatisticsResponse();

        // 获取内存使用情况
        MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
        response.setHeapMemoryUsed(memoryBean.getHeapMemoryUsage().getUsed());
        response.setHeapMemoryMax(memoryBean.getHeapMemoryUsage().getMax());
        response.setNonHeapMemoryUsed(memoryBean.getNonHeapMemoryUsage().getUsed());
        response.setNonHeapMemoryMax(memoryBean.getNonHeapMemoryUsage().getMax());

        // 获取线程信息
        response.setThreadCount(ManagementFactory.getThreadMXBean().getThreadCount());
        response.setPeakThreadCount(ManagementFactory.getThreadMXBean().getPeakThreadCount());
        response.setDaemonThreadCount(ManagementFactory.getThreadMXBean().getDaemonThreadCount());

        // 获取类加载信息
        response.setLoadedClassCount(ManagementFactory.getClassLoadingMXBean().getLoadedClassCount());
        response.setTotalLoadedClassCount(ManagementFactory.getClassLoadingMXBean().getTotalLoadedClassCount());
        response.setUnloadedClassCount(ManagementFactory.getClassLoadingMXBean().getUnloadedClassCount());

        // 获取编译信息
        response.setCompilationTime(ManagementFactory.getCompilationMXBean().getTotalCompilationTime());

        // 获取垃圾回收信息
        Map<String, Long> gcInfo = new HashMap<>();
        ManagementFactory.getGarbageCollectorMXBeans().forEach(gcBean -> {
            gcInfo.put(gcBean.getName(), gcBean.getCollectionTime());
        });
        response.setGarbageCollectionInfo(gcInfo);

        // 设置统计时间
        response.setStatisticsTime(LocalDateTime.now());

        return response;
    }

    /**
     * 获取健康检查结果
     *
     * @return 健康检查结果
     */
    public SystemMonitorDto.HealthCheckResponse getHealthCheck() {
        SystemMonitorDto.HealthCheckResponse response = new SystemMonitorDto.HealthCheckResponse();

        // 检查系统状态
        boolean systemHealthy = true;
        StringBuilder details = new StringBuilder();

        // 检查内存使用情况
        Runtime runtime = Runtime.getRuntime();
        double memoryUsageRatio = (double) (runtime.totalMemory() - runtime.freeMemory()) / runtime.maxMemory();
        if (memoryUsageRatio > 0.9) {
            systemHealthy = false;
            details.append("内存使用率过高: ").append(String.format("%.2f%%", memoryUsageRatio * 100)).append("; ");
        }

        // 检查AI服务连接状态
        boolean deepSeekConnected = deepSeekService.isAvailable();
        boolean zhipuConnected = zhipuGlmService.isAvailable();

        if (!deepSeekConnected) {
            systemHealthy = false;
            details.append("DeepSeek服务未连接; ");
        }

        if (!zhipuConnected) {
            systemHealthy = false;
            details.append("智谱GLM服务未连接; ");
        }

        // 设置响应
        response.setHealthy(systemHealthy);
        response.setCheckTime(LocalDateTime.now());
        response.setDetails(details.toString());

        // 设置各组件状态
        Map<String, Boolean> componentStatus = new HashMap<>();
        componentStatus.put("system", systemHealthy);
        componentStatus.put("deepSeek", deepSeekConnected);
        componentStatus.put("zhipu", zhipuConnected);
        response.setComponentStatus(componentStatus);

        return response;
    }
}